/****************************************************************************
**
** Copyright (C) 2013 Ernesto Barragan <ernestus at gmail dot com>
** Based on code by the Qt project:
** Copyright (C) 2012 Denis Shienkov <denis.shienkov@gmail.com>
** Copyright (C) 2012 Laszlo Papp <lpapp@kde.org>
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
****************************************************************************/

#include "settingsdialog.h"
#include "ui_settingsdialog.h"

#include <QtSerialPort/QSerialPortInfo>
#include <QIntValidator>
#include <QLineEdit>

#include <QDebug>

#ifdef Q_OS_LINUX
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#endif

QT_USE_NAMESPACE

SerialSettingsDialog::SerialSettingsDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SettingsDialog)
{
    ui->setupUi(this);

    intValidator = new QIntValidator(0, 4000000, this);

    ui->baudRateBox->setInsertPolicy(QComboBox::NoInsert);

    connect(ui->applyButton, SIGNAL(clicked()),
            this, SLOT(apply()));
    connect(ui->serialPortInfoListBox, SIGNAL(currentIndexChanged(int)),
            this, SLOT(showPortInfo(int)));
    connect(ui->baudRateBox, SIGNAL(currentIndexChanged(int)),
            this, SLOT(checkCustomBaudRatePolicy(int)));

    fillPortsParameters();
    fillPortsInfo();

    updateUi();
}

SerialSettingsDialog::~SerialSettingsDialog()
{
    delete ui;
}

void SerialSettingsDialog::showPortInfo(int idx)
{
    if (idx != -1) {
        QStringList list = ui->serialPortInfoListBox->itemData(idx).toStringList();
        ui->descriptionLabel->setText(tr("Description: %1").arg(list.at(1)));
        ui->manufacturerLabel->setText(tr("Manufacturer: %1").arg(list.at(2)));
        ui->locationLabel->setText(tr("Location: %1").arg(list.at(3)));
        ui->vidLabel->setText(tr("Vendor Identifier: %1").arg(list.at(4)));
        ui->pidLabel->setText(tr("Product Identifier: %1").arg(list.at(5)));
    }
}

void SerialSettingsDialog::apply()
{
    SerialPortSettings currentSettings ;
    currentSettings.device = ui->serialPortInfoListBox->currentText();

    // Baud Rate
    if (ui->baudRateBox->currentIndex() == ui->baudRateBox->count()-1)
    {
        // custom baud rate
        currentSettings.baudRate = ui->baudRateBox->currentText().toInt();
    }
    else
    {
        // standard baud rate
        currentSettings.baudRate = static_cast<QSerialPort::BaudRate>(
                    ui->baudRateBox->itemData(ui->baudRateBox->currentIndex()).toInt());
    }

    // Data bits
    currentSettings.dataBits = static_cast<QSerialPort::DataBits>(
                ui->dataBitsBox->itemData(ui->dataBitsBox->currentIndex()).toInt());

    // Parity
    currentSettings.parity = static_cast<QSerialPort::Parity>(
                ui->parityBox->itemData(ui->parityBox->currentIndex()).toInt());

    // Stop bits
    currentSettings.stopBits = static_cast<QSerialPort::StopBits>(
                ui->stopBitsBox->itemData(ui->stopBitsBox->currentIndex()).toInt());

    // Flow control
    currentSettings.flowControl = static_cast<QSerialPort::FlowControl>(
                ui->flowControlBox->itemData(ui->flowControlBox->currentIndex()).toInt());

    // Additional options
    currentSettings.localEchoEnabled = ui->localEchoCheckBox->isChecked();
    currentSettings.save() ;
    hide();
}

void SerialSettingsDialog::checkCustomBaudRatePolicy(int idx)
{
    bool isCustomBaudRate = !ui->baudRateBox->itemData(idx).isValid();
    ui->baudRateBox->setEditable(isCustomBaudRate);
    if (isCustomBaudRate) {
        ui->baudRateBox->clearEditText();
        QLineEdit *edit = ui->baudRateBox->lineEdit();
        edit->setValidator(intValidator);
    }
}

void SerialSettingsDialog::fillPortsParameters()
{
    // fill baud rate (is not the entire list of available values,
    // desired values??, add your independently)
    ui->baudRateBox->addItem(QLatin1String("1200"), QSerialPort::Baud1200);
    ui->baudRateBox->addItem(QLatin1String("2400"), QSerialPort::Baud2400);
    ui->baudRateBox->addItem(QLatin1String("4800"), QSerialPort::Baud4800);
    ui->baudRateBox->addItem(QLatin1String("9600"), QSerialPort::Baud9600);
    ui->baudRateBox->addItem(QLatin1String("19200"), QSerialPort::Baud19200);
    ui->baudRateBox->addItem(QLatin1String("38400"), QSerialPort::Baud38400);
    ui->baudRateBox->addItem(QLatin1String("57600"), QSerialPort::Baud57600);
    ui->baudRateBox->addItem(QLatin1String("115200"), QSerialPort::Baud115200);
    ui->baudRateBox->addItem(QLatin1String("Custom"));

    // fill data bits
    ui->dataBitsBox->addItem(QLatin1String("5"), QSerialPort::Data5);
    ui->dataBitsBox->addItem(QLatin1String("6"), QSerialPort::Data6);
    ui->dataBitsBox->addItem(QLatin1String("7"), QSerialPort::Data7);
    ui->dataBitsBox->addItem(QLatin1String("8"), QSerialPort::Data8);
    ui->dataBitsBox->setCurrentIndex(3);

    SerialPortSettings settings ;
    // fill parity
    foreach( QSerialPort::Parity i, settings.parityToString().keys() )
    {
        ui->parityBox->addItem(settings.parityToString()[i],i) ;
    }

    // fill stop bits
    foreach( QSerialPort::StopBits i, settings.stopBitsToString().keys() )
    {
        ui->stopBitsBox->addItem(settings.stopBitsToString()[i],i) ;
    }


    // fill flow control
    foreach( QSerialPort::FlowControl i, settings.flowControlToString().keys() )
    {
        ui->flowControlBox->addItem(settings.flowControlToString()[i],i) ;
    }
}

void SerialSettingsDialog::fillPortsInfo()
{
    ui->serialPortInfoListBox->clear();
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
        QStringList list;
    #ifdef Q_OS_LINUX
        //@note: the original function overpopulated the list with nonexistent ports.
        //here we avoid adding them if they don't exist. eb
        int fd ;
        struct termios old_termios;
        if ( -1 != (fd = ::open(info.systemLocation().toLatin1(), O_RDWR | O_NOCTTY | O_NDELAY)) )
        {
            qDebug() << "Opened" ;
            if (! ::tcgetattr(fd, &old_termios) )
            {
                /* only once we got the termios it can be said the port is present */
                qDebug() << "**************" ;
    #endif
                list << info.portName()
                     << info.description()
                     << info.manufacturer()
                     << info.systemLocation()
                     << (info.vendorIdentifier() ? QString::number(info.vendorIdentifier(), 16) : QString())
                     << (info.productIdentifier() ? QString::number(info.productIdentifier(), 16) : QString());

                ui->serialPortInfoListBox->addItem(list.first(), list);
    #ifdef Q_OS_LINUX
            }
            /* once finished, the device is closed */
            ::close( fd ) ;
        }
    #endif

    }
}

void SerialSettingsDialog::updateUi()
{
    SerialPortSettings settings ;
    ui->serialPortInfoListBox->setCurrentText( settings.device ) ;

    // Baud Rate
    int brIndex = ui->baudRateBox->findData( settings.baudRate );
    if ( -1 == brIndex )
    {
        // custom baud rate
        ui->baudRateBox->setCurrentIndex( ui->baudRateBox->count()-1 ) ;
        ui->baudRateBox->setCurrentText( QString("%1").arg(settings.baudRate) ) ;
    }
    else
    {
        // standard baud rate
        ui->baudRateBox->setCurrentIndex( brIndex ) ;
    }

    // Data bits
    ui->dataBitsBox->setCurrentText( QString("%1").arg(settings.dataBits) );

    // Parity
    ui->parityBox->setCurrentText( settings.parityToString()[settings.parity] );

    // Stop bits
    ui->stopBitsBox->setCurrentText( settings.stopBitsToString()[settings.stopBits]);

    // Flow control
    ui->flowControlBox->setCurrentText( settings.flowControlToString()[settings.flowControl]);

    // Additional options
    ui->localEchoCheckBox->setChecked( settings.localEchoEnabled );

}
